/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package wwcontrolserver.datarecorders;

import com.phidgets.PhidgetException;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

/**
 *
 * @author Michael Ferry
 */
public class WWControlServerLogger {
    private BufferedWriter LogWriter;
    private BufferedWriter ExceptionLogWriter;
    private final SimpleDateFormat LogEntryDateFormatter;
    private final String RecipientEmail;
    private final String SenderGmailUname;
    private final Properties GmailProps = new Properties();
    private final Session GmailSession;
    private StringBuilder WarningStringBuilder;
    public static String newline = System.getProperty("line.separator");
    private static final String WarningEmailSubjectLine = "WWControlServer - NEW WARNINGS";
    
    public WWControlServerLogger(String Path, SimpleDateFormat FileDateFormatter,
            SimpleDateFormat LogEntryDateFormatter,String RecipientEmail,final String SenderGmailUname,final String SenderGmailPass){
        this.LogEntryDateFormatter = LogEntryDateFormatter;
        this.RecipientEmail = RecipientEmail;
        this.SenderGmailUname = SenderGmailUname;
        GmailProps.put("mail.smtp.auth", "true");
        GmailProps.put("mail.smtp.starttls.enable", "true");
        GmailProps.put("mail.smtp.host", "smtp.gmail.com");
        GmailProps.put("mail.smtp.port", "587");
        
        GmailSession = Session.getInstance(GmailProps,
                new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(SenderGmailUname, SenderGmailPass);
                    }
                });
        
        //SendEmail("Hello!");
        WarningStringBuilder = new StringBuilder();
//        WarningStringBuilder.append("Hello");
//        String Test = WarningStringBuilder.toString();
//        WarningStringBuilder = null;
//        WarningStringBuilder = new StringBuilder();
//        String Test2 = WarningStringBuilder.toString();
        
        Date currTime = new Date();           
        String ServerLogFilePath = Path + FileDateFormatter.format(currTime) + "_ServerLogFile.txt";
        String ServerExceptionLogFilePath = Path + FileDateFormatter.format(currTime) + "_ServerExceptionLogFile.txt";
        try {
            LogWriter = new BufferedWriter(new FileWriter(ServerLogFilePath));
            ExceptionLogWriter = new BufferedWriter(new FileWriter(ServerExceptionLogFilePath));
            System.out.println("Log file path: " + ServerLogFilePath);
            System.out.println("Exception log file path: " + ServerExceptionLogFilePath);
            //RecordLogEntry("Server started");  
            
        } catch (IOException e) {
            System.out.println(e);
        }
    }
    
    public final void RecordLogEntry(String LogEntry){
        Date currTime = new Date();
        String OutputString;
        OutputString = LogEntryDateFormatter.format(currTime) + ": " + LogEntry;
        try{
            LogWriter.write(OutputString);
            LogWriter.newLine();
            LogWriter.flush();
        }catch (IOException e) {
            System.out.println(e);
        }  
    }
    public boolean IsWarningStringPopulated(){
        if(WarningStringBuilder.length() > 0){
            return true;
        }else{
            return false;
        }
    }
    public final void RecordWarning(String WarningString){
        Date currTime = new Date();
        String OutputString;
        OutputString = LogEntryDateFormatter.format(currTime) + ": WARNING - " + WarningString;
        
        try{
            LogWriter.write(OutputString);
            LogWriter.newLine();
            LogWriter.flush();
        }catch (IOException e) {
            System.out.println(e);
        }
        System.out.println(OutputString);
        WarningStringBuilder.append(OutputString);
        WarningStringBuilder.append(newline);
    }
    
    public void SendWarningMessage(){
        this.SendEmail(WarningEmailSubjectLine, WarningStringBuilder.toString());
        WarningStringBuilder = null;
        WarningStringBuilder = new StringBuilder();     
    }
    
    public final void RecordExceptionLogEntry(Exception ex){
        Date currTime = new Date();
        String OutputString;
        OutputString = LogEntryDateFormatter.format(currTime) + ": " + ex.toString();
        try{
            ExceptionLogWriter.write(OutputString);
            System.out.println(OutputString);
            ExceptionLogWriter.newLine();
            //write Phidget specific message
            if(ex instanceof PhidgetException){
                PhidgetException phe = (PhidgetException) ex;
                String OutMessage = phe.getDescription() + "Phidget Error " + phe.getErrorNumber();
                ExceptionLogWriter.write(OutMessage);
                ExceptionLogWriter.newLine();
            }
            StringWriter errors = new StringWriter();
            
            ex.printStackTrace(new PrintWriter(errors));
            String ExceptionErrString = errors.toString();
            ExceptionLogWriter.write(ExceptionErrString);
            ExceptionLogWriter.newLine();
            ExceptionLogWriter.flush();
            
            WarningStringBuilder.append(OutputString);
            WarningStringBuilder.append(newline);
            WarningStringBuilder.append(ExceptionErrString);
            WarningStringBuilder.append(newline);
            
        }catch (IOException e) {
            System.out.println(e);
        }  
    }
    protected final void SendEmail(String Subject, String MessageText){
                       
        try {
            MimeMessage message = new MimeMessage(GmailSession);
            message.setFrom(new InternetAddress(SenderGmailUname));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(RecipientEmail));
            message.setSubject(Subject);
            message.setText(MessageText);
            Transport.send(message);
            this.RecordLogEntry("Email sent to: " + RecipientEmail);
            
        }catch (MessagingException mex){
            this.RecordExceptionLogEntry(mex);
        }
        
        
    }
    public final void close() {
        try {
            LogWriter.close();
            ExceptionLogWriter.close();
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}
